﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using System.Globalization;
using WeifenLuo.WinFormsUI.Docking;
using System.Configuration;

namespace card
{
    public partial class Frm_cancellogin : DockContent
    {

        public static WebDG.Service ws = new card.WebDG.Service();
        string shipname = "";
        string cargoname = "";
        string yard = "";
        string stackname = "";
        string shipper_name = "";
        string cargono = "0";

        //string logintime = "";
        //string ioyardid = "1";//市提//待确认0或1
        string str_operator = "";
        //string plan_code = "1";//有计划作业

        string truckno = "";
        string truckcolor = "";
        string drivername = "";
        string driverid = "";
        string driverphone = "";
        //获取市入地址wawrdin
        static string wawrdout = ConfigurationManager.AppSettings["wawrdout"];
        //获取市提地址wawrdin
        static string wawrdin = ConfigurationManager.AppSettings["wawrdin"];
        public string cardadd
        {
            get;
            set;
        }

        public string ioyardid
        {
            get;
            set;
        }
        string str_cur_date = "";

        public Frm_cancellogin()
        {
            InitializeComponent();
        }

        private void Frm_cancellogin_Load(object sender, EventArgs e)
        {
            checkBox1.Checked = false;
            str_operator = this.Text.Substring(4);
            DateTime dt = ws.GetSysDateTime();
            dateTimePicker1.Value = dt;
            this.dataGridView1.AutoGenerateColumns = true;
            this.dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.Columns["TRUCKSTATUS"].Visible = false;

            str_cur_date = dateTimePicker1.Value.ToString("yyyy-MM-dd");
            refresh_grid();
        }
        private void refresh_grid()
        {
            string card_add = System.Configuration.ConfigurationManager.AppSettings["card_address"];
            StringBuilder sqlStr = new StringBuilder();
            sqlStr.Append("select logintime as 登记时间,truckno as  车号,QDCARDNUM as 卡号,TRUCKSTATUS from TRUCK_CARGO_LOGIN");

            if (txt_truckno_sel.Text.Length == 0)
            {
                if (checkBox1.Checked == true)
                {
                    if (ioyardid == "0" || ioyardid == "1")
                    {
                        sqlStr.AppendFormat(" where IOYARDID='{0}' and (truckstatus='0')", ioyardid);
                    }
                    else
                    {
                        sqlStr.Append(" where (truckstatus='0')");
                    }
                }
                else
                {
                    if (ioyardid == "0" || ioyardid == "1")
                    {
                        sqlStr.AppendFormat(" where to_char(logintime,'yyyy-mm-dd')='{0}' AND IOYARDID='{1}' and (truckstatus='0')", str_cur_date, ioyardid);
                    }
                    else
                    {
                        sqlStr.AppendFormat(" where to_char(logintime,'yyyy-mm-dd')='{0}' AND  (truckstatus='0')", str_cur_date);
                    }
                }
            }
            else
            {
                if (checkBox1.Checked == true)
                {
                    if (ioyardid == "0" || ioyardid == "1")
                    {
                        sqlStr.AppendFormat(" where IOYARDID='{0}' and truckno like '%{1}%' and (truckstatus='0')", ioyardid, txt_truckno_sel.Text.Trim());
                    }
                    else
                    {
                        sqlStr.AppendFormat(" where truckno like '%{0}%' and (truckstatus='0')", txt_truckno_sel.Text.Trim());
                    }
                }
                else
                {
                    if (ioyardid == "0" || ioyardid == "1")
                    {
                        sqlStr.AppendFormat(" where logintime>=to_date('{0}  00:00:00','YYYY-MM-DD HH24:MI:SS') AND logintime<=to_date('{0} 23:59:59','YYYY-MM-DD HH24:MI:SS') AND IOYARDID='{1}' and truckno like '%{2}%' and (truckstatus='0')", str_cur_date, ioyardid, txt_truckno_sel.Text.Trim());
                    }
                    else
                    {
                        sqlStr.AppendFormat(" where logintime>=to_date('{0}  00:00:00','YYYY-MM-DD HH24:MI:SS') AND logintime<=to_date('{0} 23:59:59','YYYY-MM-DD HH24:MI:SS') AND  truckno like '%{1}%' and (truckstatus='0')", str_cur_date, txt_truckno_sel.Text.Trim());
                    }
                }
            }
            sqlStr.AppendFormat(" and cardadd='{0}' group by logintime,truckno,QDCARDNUM,TRUCKSTATUS", card_add);
            DataSet ds = ws.getDataSet_Serv(sqlStr.ToString());
            dataGridView1.DataSource = ds.Tables[0];
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                dateTimePicker1.Enabled = false;
            }
            else
            {
                dateTimePicker1.Enabled = true;
            }
        }

        private void btn_select_Click(object sender, EventArgs e)
        {
            refresh_grid();
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            str_cur_date = dateTimePicker1.Value.ToString("yyyy-MM-dd");
            refresh_grid();
        }

        private void btn_exit_Click(object sender, EventArgs e)
        {
            if (this.ParentForm != null)
            {
                this.ParentForm.Close();
            }
            else
            {
                this.Close();
            } 
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
        /// <summary>
        /// 取消登记
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            #region 之前代码
            //for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            //{
            //    object obj = this.dataGridView1.Rows[i].Cells[0].Value;
            //    string select = obj == null ? "" : obj.ToString();
            //    if (select == "True")
            //    {
            //        string car_no = this.dataGridView1.Rows[i].Cells["车号"].Value.ToString();
            //        string login_time = this.dataGridView1.Rows[i].Cells["登记时间"].Value.ToString();
            //        //String update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=1,COMMANDTIME=sysdate where IOYARDID='" + ioyarid + "' and TRUCKNO='" + car_no + "'";
            //        string sql = "select bar_code,lybz from TRUCK_CARGO_LOGIN where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS='0'";
            //        DataSet ds = ws.getDataSet_Serv(sql);
            //        foreach (DataRow row in ds.Tables[0].Rows)
            //        {
            //            if (row["lybz"].ToString() == "1")
            //            {
            //                string strSQL = "insert into TRUCK_WEIGH_FLAG(TRUCKNO,BAR_CODE,WEIGH_FLAG,CZSJ) values('" + car_no + "','" + row["bar_code"].ToString() + "','0',sysdate)";
            //                ws.execute_UID_Serv(strSQL);
            //            }
            //        }
            //        string update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=9 where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS='0'";
            //        int ret2 = ws.execute_UID_Serv(update_sql);
            //        //if (ret2 > 0 && listBarCode.Count > 0)
            //        //{
            //        //    update_sql = "update dg_car_thjh set weigh_flag = '0' where cancel_flag = '0' and bar_code in ('" + string.Join("','", listBarCode.ToArray()) + "')";
            //        //    ret2 = ws.execute_UID_Serv(update_sql);
            //        //}
            //        //else
            //        //{
            //        //    MessageBox.Show("车辆【"+car_no+"】物流网提货单状态不正确，不能取消登记");
            //        //}
            //    }
            //}  
            ////string StrSql1 = "update TRUCK_LOGIN set TRUCKSTATUS='9' WHERE TRUCKNO='" + truckno + "'";
            ////string StrSql1 = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS='9' WHERE TRUCKNO='" + truckno + "'";
            ////int ret2 = ws.execute_UID_Serv(StrSql1);
            //////int ret1 = db.ExecuteNonQuery(db.GetSqlStringCommand(StrSql1.ToString()));
            ////if (ret2 == 1)
            ////{
            ////    MessageBox.Show("取消登记成功。");
            ////}
            ////else
            ////{
            ////    MessageBox.Show("取消登记失败。");
            ////}
            #endregion

            for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
            {
                object obj = this.dataGridView1.Rows[i].Cells[0].Value;
                string select = obj == null ? "" : obj.ToString();
                if (select == "True")
                {
                    string car_no = this.dataGridView1.Rows[i].Cells["车号"].Value.ToString();
                    string login_time = this.dataGridView1.Rows[i].Cells["登记时间"].Value.ToString();
                    string sql = "select bar_code,lybz from TRUCK_CARGO_LOGIN where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS='0'";
                    DataSet ds = ws.getDataSet_Serv(sql);
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        string barCode = row["bar_code"].ToString();

                        if (row["lybz"].ToString() == "1")
                        {
                            string strSQL = "insert into TRUCK_WEIGH_FLAG(TRUCKNO,BAR_CODE,WEIGH_FLAG,CZSJ) values('" + car_no + "','" + row["bar_code"].ToString() + "','0',sysdate)";
                            ws.execute_UID_Serv(strSQL);
                            if (ioyardid == "0")
                            {
                                String update_dg_sql = "update dg_car_thjh set weigh_flag=0 where BAR_CODE='" + barCode + "'";
                                int ret1 = ws.execute_UID_Serv(update_dg_sql);
                                //******************************************************//
                                //顺便调用电商平台的webservice，更新电商平台的车辆状态。//
                                //******************************************************//
                                HttpReValue rv = HttpClass.PostWebApiResult<HttpReValue>(wawrdout + string.Format("?bar_code={0}&car_state={1}", barCode, 0));
                
                                if (rv.type != "success")
                                {
                                    MessageBox.Show(rv.content);
                                    //return;
                                }
                            }
                            else
                            {
                                String update_dg_sql = "update dg_car_thjh set weigh_flag=0 where BAR_CODE='" + barCode + "'";
                                int ret1 = ws.execute_UID_Serv(update_dg_sql);
                                //******************************************************//
                                //顺便调用电商平台的webservice，更新电商平台的车辆状态。//
                                //******************************************************//
                                HttpReValue rv = HttpClass.PostWebApiResult<HttpReValue>(wawrdin + string.Format("?bar_code={0}&car_state={1}", barCode, 0));

                                if (rv.type != "success")
                                {
                                    MessageBox.Show(rv.content);
                                    //return;
                                }
                                
                            }

                        }
                    }
                    string update_sql = "update TRUCK_CARGO_LOGIN set TRUCKSTATUS=9 where logintime=to_date('" + login_time + "','yyyy-mm-dd hh24:mi:ss') and TRUCKNO='" + car_no + "' and TRUCKSTATUS='0'";
                    int ret2 = ws.execute_UID_Serv(update_sql);

                }
            } 
            //1、已过重车辆不能修改、删除、作废；
            //2、历史登记信息作废；
            //3、更新电商平台车辆状态（dg_car_thjh的cancel_flag）为“已作废”，cancel_time为系统时间。

            refresh_grid();
        }

        private void Frm_cancellogin_FormClosed(object sender, FormClosedEventArgs e)
        {


        }

        private void SetDataGridViewRowXh(DataGridViewRowPostPaintEventArgs e, DataGridView dataGridView)
        {

        }

        private void dataGridView1_RowPostPaint_1(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            //SetDataGridViewRowXh(e, dataGridView1);
        }
    }
}
